<template>
  <!-- 非配电结构企业&采集方式：网关、dtu & 设备类型：0,1,3,6,7,8-->
  <Row>
    <Col :span="24">
      <Table border :columns="columns" :data="tableData" size="small" />
      <Modal v-model="dialogvisible" title="修改设备信息">
        <Form :rules="rules" :model="formData" ref="formRef" label-width="120">
          <FormItem label="所属企业:">
            <Select v-model="formData.companyId" disabled>
              <Option
                v-for="item in companyList"
                :value="item.id"
                :key="item.value"
                :label="item.name"
              />
            </Select>
          </FormItem>
          <FormItem label="所属区域:" prop="groupId">
            <Select v-model="formData.groupId">
              <Option
                v-for="item in groupList"
                :value="item.id"
                :key="item.value"
                :label="item.name"
              />
            </Select>
          </FormItem>
          <FormItem label="设备ID:" prop="deviceId">
            <Input
              v-model.trim="formData.deviceId"
              placeholder="请输入设备ID..."
            />
          </FormItem>
          <FormItem label="设备类型:">
            <Select v-model="formData.deviceType" disabled>
              <Option
                v-for="(item, index) in deviceTypes"
                :value="item.id"
                :key="index"
                :label="item.name"
              ></Option>
            </Select>
          </FormItem>
          <FormItem label="采集方式:">
            <Select v-model="formData.collectType" disabled>
              <Option
                v-for="item in collectTypes"
                :value="item.desCode"
                :key="item.index"
                :label="item.des"
              ></Option>
            </Select>
          </FormItem>
          <FormItem label="设备名称:" prop="name">
            <Input
              v-model.trim="formData.name"
              placeholder="请输入设备名称..."
            />
          </FormItem>
          <FormItem label="设备别名:" prop="alias">
            <Input
              v-model.trim="formData.alias"
              placeholder="请输入设备别名..."
            />
          </FormItem>
          <FormItem label="设备位置:" prop="location">
            <Input
              v-model.trim="formData.location"
              placeholder="请输入设备位置..."
            />
          </FormItem>
          <FormItem label="网关端口:" v-if="!isDtu">
            <Select
              v-model="formData.gatewayPort"
              placeholder="请选择网关端口..."
              disabled
            >
              <Option
                v-for="item in gatewayPortList"
                :value="item.port"
                :key="item.port"
                :label="item.port"
              />
            </Select>
          </FormItem>
          <FormItem label="网关地址码:" prop="gatewayCode" v-if="!isDtu">
            <InputNumber
              v-model="formData.gatewayCode"
              placeholder="请输入网关地址码..."
              style="width:100%;"
            />
          </FormItem>

          <!--  -->
          <FormItem label="串口地址码：" prop="stata_addr">
            <InputNumber
              v-model="formData.stata_addr"
              placeholder="请输入串口地址码..."
              style="width:100%;"
            />
          </FormItem>
          <FormItem label="串口端口：">
            <InputNumber
              v-model="formData.stata_port"
              placeholder="请输入串口端口..."
              style="width:100%;"
              disabled
            />
          </FormItem>

          <!--  -->
          <FormItem label="采集频率">
            <Input v-model="formData.rate" disabled />
          </FormItem>
          <FormItem label="断路功能:" prop="disconState">
            <i-switch v-model="formData.disconState">
              <span slot="open">On</span>
              <span slot="close">Off</span>
            </i-switch>
          </FormItem>
          <FormItem label="是否启用:" prop="enable">
            <i-switch v-model="formData.enable">
              <span slot="open">On</span>
              <span slot="close">Off</span>
            </i-switch>
          </FormItem>

          <!--  -->
          <FormItem label="是否接入零线：">
            <i-switch v-model="formData.lineToZeroLine" disabled>
              <span slot="open">On</span>
              <span slot="close">Off</span>
            </i-switch>
          </FormItem>
          <FormItem
            label="零线设备显示："
            prop="showZeroLine"
            v-if="formData.childDeviceName"
          >
            <i-switch v-model="formData.showZeroLine" disabled>
              <span slot="open">On</span>
              <span slot="close">Off</span>
            </i-switch>
          </FormItem>

          <FormItem label="零线设备名称：" v-if="formData.childDeviceName">
            <Input
              v-model="formData.childDeviceName"
              placeholder="请输入零线设备名称..."
              disabled
            />
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="onCancle">取消</Button>
          <Button type="primary" @click="onSubmit">完成</Button>
        </div>
      </Modal>
    </Col>
  </Row>
</template>
<script>
import {
  getCompanyListOfNew,
  getGroupList,
  getDeviceType,
  getGatewayType,
  getGatewayList,
  editDevice
} from "@/api";
import { generateRules } from "../utils";
function filterText(bool) {
  if (bool) {
    return {
      text: "是",
      color: "success"
    };
  }
  return {
    text: "否",
    color: "error"
  };
}
const gatewayParams = [
  {
    title: "网关端口",
    align: "center",
    key: "gatewayPort"
  },

  {
    title: "网关地址码",
    align: "center",
    key: "gatewayCode"
  }
];

const lingXian = [
  {
    title: "零线显示设备",
    align: "center",
    key: "lineToZeroLine",
    render(h, { row: { lineToZeroLine } }) {
      return h("span", lineToZeroLine ? "是" : "否");
    }
  }
];

function genColumns(vm) {
  return [
    {
      title: "所属企业",
      key: "company",
      align: "center"
    },
    {
      title: "所属区域",
      key: "group",
      align: "center"
    },
    {
      title: "采集方式",
      align: "center",
      render(h, params) {
        const { collectType } = params.row,
          result = vm.collectTypeList.find(t => t.desCode === collectType),
          text = result ? result.des : "";
        return h("span", text);
      }
    },
    {
      title: "设备名称",
      align: "center",
      key: "name"
    },
    {
      title: "设备别名",
      align: "center",
      key: "alias"
    },
    {
      title: "串口端口",
      align: "center",
      key: "stata_port"
    },
    {
      title: "串口地址码",
      align: "center",
      key: "stata_addr"
    },
    {
      title: "设备位置",
      align: "center",
      key: "location"
    },
    {
      title: "设备ID",
      align: "center",
      key: "deviceId"
    },
    {
      title: "是否断路",
      align: "center",
      render: (h, params) => {
        const { disconState } = params.row;
        const { text, color } = filterText(disconState);
        return h(
          "Tag",
          {
            props: {
              color
            }
          },
          text
        );
      }
    },
    {
      title: "是否启用",
      align: "center",
      render: (h, params) => {
        const { enable } = params.row;
        const { text, color } = filterText(enable);
        return h(
          "Tag",
          {
            props: {
              color
            }
          },
          text
        );
      }
    },
    {
      title: "采集频率",
      align: "center",
      render: (h, params) => h("span", params.row.collectRate + "分钟")
    }
  ];
}

function genOperClounms(vm) {
  return {
    title: "操作",
    align: "center",
    render: (h, params) => {
      return h(
        "Button",
        {
          props: {
            type: "error",
            size: "small"
          },
          on: {
            click: () => {
              vm.handelEdit(params.row);
            }
          }
        },
        "编辑"
      );
    }
  };
}

export default {
  mounted() {
    this.initState();
  },
  props: {
    row: {
      type: Object,
      default: new Object()
    },
    isDtu: {
      type: Boolean,
      default: false
    },
    collectTypeList: {
      type: Array,
      default: new Array()
    }
  },
  watch: {
    row: {
      deep: true,
      handler() {
        this.initState();
      }
    }
  },
  data() {
    return {
      columns: [],
      tableData: [],
      companyList: [],
      groupList: [],
      deviceTypes: [],
      collectTypes: [],
      gatewayPortList: [],
      formData: {},
      dialogvisible: false,
      rules: generateRules()
    };
  },
  methods: {
    initState() {
      const columns = genColumns(this);
      const row = JSON.parse(JSON.stringify(this.row));
      if (!this.isDtu) {
        this.columns = columns.concat(gatewayParams);
      } else {
        this.columns = columns;
      }
      if (row.lineToZeroLine) {
        this.columns = columns.concat(lingXian);
      }
      this.columns = this.columns.concat(genOperClounms(this));

      row["rate"] = row.collectRate;
      row["stata_port"] = row.stataPort;
      row["stata_addr"] = row.stataAddr;
      row["showZeroLine"] = row.childDeviceName ? true : false;

      this.tableData = [row];
    },

    // 编辑
    handelEdit(row) {
      this.dialogvisible = true;
      this.$refs.formRef.resetFields();
      this.formData = JSON.parse(JSON.stringify(row));
      this.formData["rate"] = row.collectRate;
      this.getCompanyList();
      this.getGroupList(row.companyId);
      this.getDeviceTypeList();
      this.getCollectTypeList();
      if (!this.isDtu) {
        let collectType = row.collectType;
        this.getGatewayTypeList(collectType);
      }
    },

    onCancle() {
      this.dialogvisible = false;
    },
    onSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          let params = {
            ...this.formData
          };
          editDevice(params).then(res => {
            if (res.code === 200) {
              this.$Message.success("操作成功");
              this.dialogvisible = false;
              this.initState();
              this.$emit("afterSave");
            } else {
              this.$Message.error(res.message);
            }
          });
        }
      });
    },

    getCompanyList() {
      const vm = this;
      const params = {
        page: 1,
        size: 1000
      };
      getCompanyListOfNew(params).then(res => {
        if (res.code === 200) {
          vm.companyList = res.data.list;
        } else {
          vm.companyList = [];
        }
      });
    },

    getGroupList(companyId) {
      const vm = this;
      getGroupList({ companyId }).then(res => {
        if (res.code === 200) {
          vm.groupList = res.data.list;
        }
      });
    },

    // 获取设备类型列表
    getDeviceTypeList() {
      getDeviceType().then(res => {
        if (res.code === 200) {
          this.deviceTypes = res.data;
        }
      });
    },

    // 获取采集类型列表
    getCollectTypeList() {
      getGatewayType().then(res => {
        if (res.code === 200) {
          this.collectTypes = res.data;
        }
      });
    },

    // 网关端口
    getGatewayTypeList(type) {
      if (type && type !== 0) {
        const params = { type };
        getGatewayList({ params }).then(res => {
          this.gatewayPortList = res.data;
        });
      }
    }
  }
};
</script>
